package com.winchain.provider;

import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.base.utils.SystemUtil.SystemMode;
import com.shell.feign.PubParameterFeign;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.vo.ParameterVo;
import com.winchain.chainbill.basic.activity.po.BasAct;
import com.winchain.chainbill.basic.activity.po.BasCusCpn;
import com.winchain.chainbill.basic.activity.service.BasActService;
import com.winchain.chainbill.basic.activity.service.BasCusCpnService;
import java.text.ParseException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ActivityUpdateProvider {
	private final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private PubParameterFeign pubParameterFeign;
	@Autowired
	private BasActService basActService;
	@Autowired
	private BasCusCpnService basCusCpnService;

	@RequestMapping({ "/activityUpdate/update" })
	public void update() {
		String workDate = SysDateUtil.getSystemDate();
		if (!SystemUtil.SystemMode.prod.equals(SystemUtil.getSystemMode())) {
			ParameterVo parameter = this.pubParameterFeign.getCommonParameter("SYS_DATE_CONF");
			if ((parameter != null) && (!StringUtil.emptyAndNull(parameter.getParmValue()))) {
				workDate = parameter.getParmValue();
			}
		}
		updateStartActivity(workDate);

		String preDate = null;
		try {
			preDate = SysDateUtil.getPreDay(workDate, -1);
		} catch (ParseException e) {
			this.logger.error("��������������", e);
		}
		updateEndActivity(preDate);

		updateEndCusCpn(preDate);
	}

	private void updateEndCusCpn(String workDate) {
		BasCusCpn tmpCpn = null;
		tmpCpn = new BasCusCpn();
		tmpCpn.setEndDate(workDate);
		tmpCpn.setCpnSts("1");
		List<BasCusCpn> cpns = this.basCusCpnService.selectByEntity(tmpCpn);
		for (BasCusCpn cpn : cpns) {
			cpn.setCpnSts("0");
			this.basCusCpnService.updateNotNull(cpn);
		}
	}

	private void updateEndActivity(String workDate) {
		BasAct tmp = new BasAct();
		tmp.setEndDate(workDate);
		List<BasAct> actList = this.basActService.selectByEntity(tmp);
		for (BasAct act : actList) {
			act.setActSts("3");
			this.basActService.updateNotNull(act);
		}
	}

	private void updateStartActivity(String workDate) {
		BasAct tmp = new BasAct();
		tmp.setStrtDate(workDate);
		tmp.setActSts("0");
		List<BasAct> actList = this.basActService.selectByEntity(tmp);
		for (BasAct act : actList) {
			act.setActSts("1");
			this.basActService.updateNotNull(act);
		}
	}
}
